<!-- 加速终端 -->
<template>
  <div class="dashboard-editor-container">
    <el-row style="background: #fff; padding: 16px 16px 0;">
      <div class="top">
        <div class="title">已注册终端</div>
        <el-button class="btn" type="primary" @click="addTerminal()">添加终端</el-button>
      </div>
      <div>
        <el-table border stripe :data="tableData"  style="width: 100%; margin: 15px 0">
          <el-table-column type="index" width="80" label="序号" ></el-table-column>
          <el-table-column prop="Department" label="从属部门" show-overflow-tooltip></el-table-column>
          <el-table-column prop="Name" show-overflow-tooltip label="终端名称" ></el-table-column>
          <el-table-column prop="RealnameFix" show-overflow-tooltip  width="180" label="硬件标识" ></el-table-column>
          <el-table-column prop="Mobile" show-overflow-tooltip width="160" label="手机号码" ></el-table-column>
          <el-table-column prop="ComputerName" show-overflow-tooltip width="180" label="计算机名称" ></el-table-column>
          <el-table-column prop="OsInfo" show-overflow-tooltip width="140" label="操作系统" ></el-table-column>
          <el-table-column prop="PolicyLevel" label="用户角色" show-overflow-tooltip width="100">
            <template slot-scope="props">
              <span>{{ props.row.PolicyLevel === 0 ? '普通员工' : props.row.PolicyLevel === 1 ? '部门主管' : '销售总监' }}</span>
            </template>
          </el-table-column>
          <el-table-column show-overflow-tooltip label="开通业务" >
            <!-- <template slot-scope="props">
              <span>{{ props.row.RightDC === 1 ? '行为分析、' : '' }}</span>
              <span>{{ props.row.RightAMazon === 1 ? '亚马逊助手、' : '' }}</span>
              <span>{{ props.row.RightAI === 1 ? 'AI助手、' : '' }}</span>
              <span>{{ props.row.RightV2ray === 1 ? '网络加速、' : '' }}</span>
              <span>{{ props.row.RightData === 1 ? '精准资源' : '' }}</span>
            </template> -->
            <template slot-scope="props">
              <span>{{ props.row.RightDC === 1 ? '行为、' : '' }}</span>
              <span>{{ props.row.RightAMazon === 1 ? '助手、' : '' }}</span>
              <span>{{ props.row.RightAI === 1 ? 'AI、' : '' }}</span>
              <span>{{ props.row.RightV2ray === 1 ? '加速、' : '' }}</span>
              <span>{{ props.row.RightData === 1 ? '资源' : '' }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作"  width="250px" fixed="right">
            <template slot-scope="scope">
              <el-button size="mini" type="primary" @click="handleEdit(scope.row)">修改</el-button>
              <el-button size="mini" type="danger" @click="handleDelete(scope.row)">删除</el-button>
              <el-button size="mini" type="success" @click="handleOpenAI(scope.row)">AI页面</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="title">申请终端</div>
      <div>
        <el-table border stripe :data="RegEmployeeData"  style="width: 100%; margin: 15px 0">
          <el-table-column type="index" width="80" label="序号" ></el-table-column>
          <el-table-column prop="TransTime" label="申请时间" align="left" width="170" show-overflow-tooltip></el-table-column>
          <el-table-column prop="Department" label="从属部门" show-overflow-tooltip></el-table-column>
          <el-table-column prop="Name" label="终端名称" align="left" show-overflow-tooltip></el-table-column>
          <el-table-column prop="Mobile" label="手机号码" show-overflow-tooltip></el-table-column>
          <el-table-column prop="ComputerName" label="计算机名称" show-overflow-tooltip></el-table-column>
          <el-table-column prop="OsInfo" label="操作系统" show-overflow-tooltip></el-table-column>
          <el-table-column prop="DeviceIP" label="IP地址" align="left" show-overflow-tooltip></el-table-column>
          <el-table-column prop="HardID" label="硬件标识" show-overflow-tooltip></el-table-column>
          <!-- <el-table-column prop="PolicyLevel" label="用户角色" show-overflow-tooltip width="100">
            <template slot-scope="props">
              <span v-if="props.row.PolicyLevel">{{ props.row.PolicyLevel === 0 ? '普通员工' : props.row.PolicyLevel === 1 ? '部门主管' : '销售总监' }}</span>
              <span v-else>--</span>
            </template>
          </el-table-column> -->
          <el-table-column label="操作" align="left" width="150px" fixed="right">
            <template slot-scope="scope">
              <el-button size="mini" type="primary" @click="handleregister(scope.row)">注册</el-button>
              <el-button size="mini" type="danger" @click="handleregisterDelete(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-row>
    
    <el-dialog
      :close-on-click-modal="false" 
      :close-on-press-escape=false
      title="AI"
      :visible.sync="openAIDialog"
      v-el-drag-dialog
      width="45%">
      <el-link :underline="false" type="primary" @click="copyAIUrl()">{{ AIUrl }}</el-link>
      <br/>
      <!-- <el-link :underline="false" type="primary">{{ AIUrl2 }}</el-link> -->
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="copyAIUrl()" style="margin-left:20px">拷贝链接</el-button>
        <el-button type="info" @click="openAIDialog = false">取 消</el-button>
      </span>
    </el-dialog>
    <el-dialog
      :close-on-click-modal="false" 
      :close-on-press-escape=false
      :title="title"
      :visible.sync="dialogVisible"
      v-el-drag-dialog
      width="45%">
      <el-form label-width="120px" :model="RegEmployeeForm" :rules="rules" ref="RegEmployeeForm">
        <el-row>
          <el-col :span="12">
            <el-form-item label='终端名称:' prop="Name">
              <el-input v-model="RegEmployeeForm.Name" :disabled="title==='修改终端'" maxlength="16"></el-input>
            </el-form-item>
          </el-col>
          <el-col  :span="12">
            <el-form-item label='从属部门:' class="cascader" prop="Department">
              <el-cascader
                ref="cascaderAddr"
                style="width:100%;"
                v-model="RegEmployeeForm.Department"
                placeholder="请选择部门"
                clearable
                :disabled="title === '修改终端'"
                :show-all-levels="false"
                :options="options"
                :props="{ expandTrigger: 'hover', label: 'DepartmentName', value: 'DepartmentName', ID: 'ID'}"
                @change="handleChange">
              </el-cascader>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label='手机号码:' prop="Mobile">
              <el-input v-model="RegEmployeeForm.Mobile" oninput ="value=value.replace(/[^0-9]/g,'')" maxlength="11"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label='计算机名称:' prop="ComputerName">
              <el-input v-model="RegEmployeeForm.ComputerName" :disabled="title !== '添加终端'"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label='操作系统:' prop="OsInfo">
              <el-input v-model="RegEmployeeForm.OsInfo" :disabled="title !== '添加终端'"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label='硬件标识:' prop="RealnameFix">
              <el-input v-model="RegEmployeeForm.RealnameFix"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="用户角色：" prop="RealnameFix">
              <el-radio-group v-model="RegEmployeeForm.PolicyLevel">
                <el-radio :label="0">普通员工</el-radio>
                <el-radio :label="1">部门主管</el-radio>
                <el-radio :label="2">销售总监</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label='开通业务:' prop="Right">
              <el-checkbox v-model="RegEmployeeForm.RightDC" :true-label=1 :false-label=0 :disabled="Right[0] === '0'">开通行为分析</el-checkbox>
              <el-checkbox v-model="RegEmployeeForm.RightAMazon" :true-label=1 :false-label=0 :disabled="Right[2] === '0'">开通亚马逊助手</el-checkbox>
              <el-checkbox v-model="RegEmployeeForm.RightAI" :true-label=1 :false-label=0 :disabled="Right[3] === '0'">开通AI助手</el-checkbox>
              <el-checkbox v-model="RegEmployeeForm.RightV2ray" :true-label=1 :false-label=0 :disabled="Right[4] === '0'">开通网络加速</el-checkbox>
              <el-checkbox v-model="RegEmployeeForm.RightData" :true-label=1 :false-label=0 :disabled="Right[5] === '0'">开通精准资源</el-checkbox>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submit()">确 定</el-button>
        <el-button type="info" @click="dialogVisible = false">取 消</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { connrequest } from "@/api/firstPage"
import elDragDialog from '@/directive/el-drag-dialog' // base on element-ui
import { treeing, getTreeData, parseTime } from "@/utils/index.js";
import { isArray } from '@/utils/validate';
export default {
  directives: { elDragDialog },
  data() {
    return {
      title: '',
      AIUrl: '',
      AIUrl2: '',
      Right: ['0', '0', '0', '0', '0', '0'],
      dialogVisible: false,
      openAIDialog: false,
      RegEmployeeForm:{},
      options: [],
      tableData: [],
      RegEmployeeData: [],
      terminalName: [],
      RealnameFix: [],
      isadd: false,
      DID:'',
      rules:{
        Name: [
          { required: true, message: '请输入终端名称'}
        ],
        Department: [
          { required: true, message: '请选择从属部门', trigger: 'change'}
        ],
        Mobile:[
          {
            validator: function(rule, value, callback) {
              if (/^1[34578]\d{9}$/.test(value) == false && value) {
                callback(new Error("手机号格式错误"));
              } else {
                callback();
              }
            },
            trigger: "blur"
          }
        ]
      }
    }
  },
  //生命周期 - 创建完成（访问当前this实例）
  created() {
    this.GetDepartment()
    this.GetRegEmployee()
    this.GetDCDInfo()
  },
  //生命周期 - 挂载完成（访问DOM元素）
  mounted() {},
  methods: {
    async GetDCDInfo() {
      const res = await connrequest('GetDCDInfo')
      this.Right = res.Data.Right ? res.Data.Right.split(' ')[0].split('') : ['0','0','0','0','0','0',]
    },
    async GetEmployee(){
      let terminalName = []
      let RealnameFix = []
      const res = await connrequest('GetEmployee')
      res.Data = res.Data || []
      res.Data = res.Data.map(item=>{
        item.RealnameType = item.RealnameType == '1' ? 'mac' : 'ip'
        terminalName.push(item.Name)
        RealnameFix.push(item.RealnameFix)
        return item
      })
      this.tableData = res.Data
      // 保存所有终端名称和准入模式
      this.terminalName = terminalName  
      this.RealnameFix = RealnameFix
    },
    async GetRegEmployee(){
      const res = await connrequest('GetRegEmployee')
      res.Data = res.Data || []
      res.Data = res.Data.map(item=>{
        item.TransTime = parseTime(item.TransTime)
        return item
      })
      this.RegEmployeeData = res.Data
    },
    // 添加终端
    addTerminal(){
      this.title = '添加终端'
      this.$nextTick(()=>{
        this.$refs['RegEmployeeForm'].clearValidate()
      })
      this.RegEmployeeForm = {
        RightDC: 0,
        RightAMazon: 0,
        RightAI: 0,
        RightV2ray: 0,
        RightData: 0,
        PolicyLevel: 0
      }
      this.dialogVisible = true
    },
    copyAIUrl(){
      let elInput = document.createElement('textarea')
      elInput.value = this.AIUrl
      document.body.appendChild(elInput)
      // 选择对象
      elInput.select()
      // 执行浏览器复制命令
      this.$message.success('复制成功')
      document.execCommand("Copy")
      elInput.remove()
    },
    handleOpenAI(row){
      let userid = Buffer.from(row.Name).toString('base64')
      this.AIUrl = `https://${window.location.hostname}:8443/#/AI?userid=${userid}`
      this.AIUrl2 = `https://${window.location.hostname}:6443/#/login?userid=${userid}`
      // this.AIUrl = `${process.env.VUE_APP_BASE_API}:8443/#/AI?userid=${userid}`
      // this.AIUrl = `http://192.168.20.159:8443/#/AI?userid=${userid}`
      this.openAIDialog = true
    },
    handleEdit(row){
      this.title = '修改终端'
      this.$nextTick(()=>{
        this.$refs['RegEmployeeForm'].clearValidate()
      })
      row.RealnameType = row.RealnameType === 'mac' ? '1' : '2'
      // row.Department = [row.Department]
      this.RegEmployeeForm = {...row}
      this.dialogVisible = true
    },
    handleregister(row){
      console.log(row);
      console.log(row.Department);
      let Department = Array.isArray(row.Department)
      console.log(Department);
      this.title = '注册终端'
      this.$nextTick(()=>{
        this.$refs['RegEmployeeForm'].clearValidate()
      })
      row.Name = row.Name
      row.RealnameType = '2'
      row.RealnameFix = row.HardID
      // row.Department = row.Department ? [row.Department] : null
      row.Department = row.Department
      row.RightDC = 0
      row.RightAMazon = 0
      row.RightAI = 0
      row.RightV2ray = 0
      row.RightData = 0
      row.PolicyLevel = 0
      this.registerform = row
      this.RegEmployeeForm = {...row}
      this.dialogVisible = true
    },
    handleDelete(row){
      this.$confirm('此操作将永久删除该终端, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then( async () => {
        row.RealnameType = row.RealnameType === 'mac' ? 1 : 2
        const data = {
          Data:{
            ...row
          }
        }
        const res = await connrequest('DelEmployee', data)
        if(res.Status.StatusCode === 0){
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
          this.GetEmployee()
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });          
      });
    },
    handleregisterDelete(row){
      this.$confirm('此操作将永久删除该终端, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then( async () => {
        const data = {
          Data:{
            HardID: row.HardID
          }
        }
        const res = await connrequest('DelRegEmployee', data)
        if(res.Status.StatusCode === 0){
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
          this.GetRegEmployee()
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });          
      });
    },
    async GetDepartment(){
      const res = await connrequest('GetDepartment')
      this.options = getTreeData(treeing(res.Data))
      this.GetEmployee()
    },
    handleChange(arr,node){
      let DID = this.$refs['cascaderAddr'].getCheckedNodes()[0].data.ID
      this.DID = DID
    },
    // elCascaderOnlick(){
    //   let that = this;
    //   setTimeout(function() {
    //     document.querySelectorAll(".el-cascader-node__label").forEach((el) => {
    //       el.onclick = function() {
    //         this.previousElementSibling.click();
    //         that.$refs.cascaderAddr.dropDownVisible = false;
    //       };
    //     });
    //   }, 100);
    // },
    submit(){
      this.$refs['RegEmployeeForm'].validate( async(valid) => {
        if(valid){
          if(this.title === '添加终端' || this.title === '注册终端'){
            console.log(this.terminalName);
            let terminalName = this.terminalName.filter(item => { return item === this.RegEmployeeForm.Name })
            if(terminalName.length > 0){
              this.$message.error('该终端名称已经存在')
              return false
            }
            if(Array.isArray(this.RegEmployeeForm.Department)){
              this.RegEmployeeForm.Department = this.RegEmployeeForm.Department[this.RegEmployeeForm.Department.length - 1]
            }
            let data = {
              Data:{
                ...this.RegEmployeeForm,
                DID: this.DID
              }
            }
            const res = await connrequest('AddEmployee', data)
            if(res.Status.StatusCode === 0){
              if(this.title === '注册终端'){
                const data = {
                  Data:{
                    HardID: this.registerform.HardID
                  }
                }
                await connrequest('DelRegEmployee', data)
                this.GetRegEmployee()
              }
              this.$message({
                type: 'success',
                message: '添加终端成功'
              });
              this.GetEmployee()
              this.dialogVisible = false
            }
          }else{
            if(Array.isArray(this.RegEmployeeForm.Department)){
              this.RegEmployeeForm.Department = this.RegEmployeeForm.Department[this.RegEmployeeForm.Department.length - 1]
            }
            this.RegEmployeeForm.RealnameType = this.RegEmployeeForm.RealnameType * 1
            let data = {
              Data:{
                ...this.RegEmployeeForm
              }
            }
            const res = await connrequest('ModifyEmployee', data)
            if(res.Status.StatusCode === 0){
              this.$message({
                type: 'success',
                message: '修改终端成功'
              });
              this.GetEmployee()
              this.dialogVisible = false
            }
          }
        }
      })
    },
  }
}
</script>
<style scoped lang='scss'>
/* @import url(); 引入css类 */
.top{
  display:flex;
  justify-content:space-between;
  align-items: center;
}
// /* cascader 隐藏单选样式 start */
// 	::v-deep .cascader .el-cascader-panel .el-radio {
// 		display: none !important;
// 	}
</style>
<style>
.el-cascader-panel .el-radio {
  display: none;
}
.demo-table-expand {
  font-size: 0;
}
.demo-table-expand label {
  color: #99a9bf;
}
.demo-table-expand .el-form-item {
  margin-right: 0;
  margin-bottom: 0;
  width: 50%;
}
</style>